package cn.zy.amyan.server.handler;

import cn.zy.amyan.core.base.RequestData;
import cn.zy.amyan.core.base.ResponseData;
import cn.zy.amyan.core.util.ClassUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author 子言
 * @date 2024/5/5 下午 16:11
 */
public class ServerHandler extends SimpleChannelInboundHandler<RequestData> {

	private static final Logger log = Logger.getLogger("appLogger");
	private static final Map<Class<?>, Object> OBJECT_MAP = new HashMap<>();

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RequestData msg) throws Exception {
		ResponseData responseData = new ResponseData();
		responseData.setRequestId(msg.getRequestId());
		log.info("开始处理消息：requestId = " + msg.getRequestId());

		try {
			Class<?> clazz = Class.forName(msg.getClassName());
			if(!OBJECT_MAP.containsKey(clazz)) {
				// 获取接口实现类，这里只获取第一个，其它的忽略
				ArrayList<Class> allClassByInterface = ClassUtil.getAllClassByInterface(clazz);
				for (Class c : allClassByInterface) {
					OBJECT_MAP.put(clazz, c.newInstance());
					break;
				}
			}
			// 获取方法
			Method method = clazz.getMethod(msg.getMethodName(), msg.getParameterTypes());
			method.setAccessible(true);
			Object result = method.invoke(OBJECT_MAP.get(clazz), msg.getParameters());
			log.info("返回结果：result = " + result);
			responseData.setResult(result);

		} catch (Exception e) {
			log.severe("处理失败... requestId = " + msg.getRequestId());
			responseData.setErrorMsg("error");
		}
		ctx.writeAndFlush(responseData);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		log.severe("断开连接");
		// 关闭连接
		ctx.close();
	}
}
